package com.dq.service.order.impl;

import com.dq.context.Constant;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.OrgOrderQuery;
import com.dq.controller.in.base.BaseAdminQuery;

import com.dq.domain.orders.OrgOrder;
import com.dq.domain.orders.info.OrderInfo;
import com.dq.domain.org.Org;
import com.dq.domain.goods.stock.StockChangeRecord;
import com.dq.domain.sys.section.SysSection;
import com.dq.domain.sys.user.user.BossUser;
import com.dq.domain.sys.user.user.OrgUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.repository.BaseRepositories;
import com.dq.service.messsge.ApprovalMessageService;
import com.dq.service.order.OrgOrderService;
import com.dq.service.org.OrgService;
import com.dq.service.section.impl.SysSectionServiceImpl;
import com.dq.service.sys.user.BossUserService;
import com.dq.utils.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @author liuhui
 * @date 2019/11/27 0027 13:36:20
 */
@Service
public class OrgOrderServiceImpl extends BaseRepositories implements OrgOrderService {

    @Autowired
    private OrgService orgService;
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private BossUserService bossUserService;
    @Autowired
    private ApprovalMessageService approvalMessageService;
    @Autowired
    private SysSectionServiceImpl sysSectionService;


    @Override
    public List<OrgOrder> findByWhere(OrgOrderQuery orgOrderQuery, Org org, Long userId) throws AdminException {
        StringBuilder hql = new StringBuilder("select u from OrgOrder u where u.deleted=false");

        Query q = createWhereHql(orgOrderQuery, org, userId, hql);

        q.setFirstResult((orgOrderQuery.getPage()-1)*orgOrderQuery.getSize());
        q.setMaxResults(orgOrderQuery.getSize());
        List<OrgOrder> orgOrders = q.getResultList();
        return orgOrders;
    }

    @Override
    public Long countByWhere(OrgOrderQuery orgOrderQuery, Org org, Long userId) throws AdminException {
        StringBuilder hql = new StringBuilder("select count(u) from OrgOrder u where u.deleted=false");

        Query q = createWhereHql(orgOrderQuery, org, userId, hql);

        return new Long((long) q.getResultList().get(0));
    }

    public Query createWhereHql(OrgOrderQuery orgOrderQuery, Org org, Long userId, StringBuilder hql) throws AdminException {
        if(org != null) {
            hql.append(" and u.org =:org");
        }else {
            // 只显示负责门店信息
            String orgIdsIn = orgService.getIdListAllByUser();
            if(StringUtils.isNotBlank(orgIdsIn)) {
                hql.append(" and u.org.id in ").append(orgIdsIn);
            }
        }
        if(userId != null) {
            hql.append(" and u.staffUser.id =:userId");
        }
        if(StringUtils.isNotBlank(orgOrderQuery.getStaffUserName())) {
            hql.append(" and u.staffUser.userRealcName like:userRealcName");
        }
        if(StringUtils.isNotEmpty(orgOrderQuery.getOrderNo())){
            hql.append(" and u.ordersNo like:ordersNo");
        }
        if(null!=orgOrderQuery.getBeginTime()){
            hql.append(" and u.createTime >=:beginTime");
        }
        if(null!=orgOrderQuery.getEndTime()){
            hql.append(" and u.createTime <=:endTime");
        }
        if(null!=orgOrderQuery.getStatus()){
            hql.append(" and u.orgOrderStatus =:status");
        }
        hql.append(" order By u.createTime desc");

        Query query = this.entityManager.createQuery(hql.toString());

        if(org != null) {
            query.setParameter("org",org);
        }
        if(userId != null) {
            query.setParameter("userId", userId);
        }
        if(StringUtils.isNotBlank(orgOrderQuery.getStaffUserName())) {
            query.setParameter("userRealcName", BaseAdminQuery.likeSql(orgOrderQuery.getStaffUserName()));
        }

        if(StringUtils.isNotEmpty(orgOrderQuery.getOrderNo())){
            query.setParameter("ordersNo","%"+orgOrderQuery.getOrderNo()+"%");
        }
        if(null!=orgOrderQuery.getBeginTime()){
            query.setParameter("beginTime",orgOrderQuery.getBeginTime());
        }
        if(null!=orgOrderQuery.getEndTime()){
            query.setParameter("endTime",orgOrderQuery.getEndTime());
        }
        if(null!=orgOrderQuery.getStatus()){
            query.setParameter("status",orgOrderQuery.getStatus());
        }
        return query;
    }

    /**
     * 采购审核
     * @param yOrNo 确认/拒绝
     * @param remake boss 审核时的备注， 其他无需传值
     * @param orgOrderId 采购单ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrgOrder check(Boolean yOrNo, String remake, Long orgOrderId) throws AdminException {
        if(yOrNo == null) {
            throw new AdminException("审核结果为空");
        }
        SysUser loginUser = sysUserService.getUser();

        String judge = "";
        OrgOrder orgOrder = dao.get(OrgOrder.class, orgOrderId);
        if(orgOrder == null) {
            throw new AdminException("无对应id采购单");
        }

        if(orgOrder.getOrgOrderStatus().toString().equals(OrgOrder.OrgOrderStatus.submitPass.toString())) {
            judge = "你无boss审核权限";
            if(loginUser instanceof BossUser) {
                List<BossUser> bossByOrgList = bossUserService.getBossByOrg((Org) orgOrder.getOrg());
                for (BossUser bossUser : bossByOrgList) {
                    if(loginUser.getId().toString().equals(bossUser.getId().toString())) {
                        // boss审核
                        if(yOrNo) {
                            orgOrder.setOrgOrderStatus(OrgOrder.OrgOrderStatus.bossPass);
                            // 给 所有财务 发消息
                            approvalMessageService.messageToRole(orgOrderId, 2);
                        }else {
                            orgOrder.setOrgOrderStatus(OrgOrder.OrgOrderStatus.bossFefuse);
                            approvalMessageService.messageToBuyer(orgOrderId);
                        }
                        orgOrder.setRemark(remake);
                        judge = "";
                    }
                }
            }
        }else if(orgOrder.getOrgOrderStatus().toString().equals(OrgOrder.OrgOrderStatus.bossPass.toString())) {
            judge = "你无财务审批权限";
            List<String> roleCodesList = bossUserService.getRoleCodesByUser(loginUser);
            // boss审批确认 -> 财务审批
            if(ListUtils.listIn(Constant.ROLE_CODE_LIST.get(2), roleCodesList) != -1) {
                // 财务审批
                if(yOrNo) {
                    orgOrder.setOrgOrderStatus(OrgOrder.OrgOrderStatus.financialPass);
                    // 给 所有仓库 发消息
                    approvalMessageService.messageToRole(orgOrderId, 1);
                }else {
                    orgOrder.setOrgOrderStatus(OrgOrder.OrgOrderStatus.financialRefuse);
                    approvalMessageService.messageToBuyer(orgOrderId);
                }
                judge = "";
            }
        }else if(orgOrder.getOrgOrderStatus().toString().equals(OrgOrder.OrgOrderStatus.financialPass.toString())) {
            judge = "你无仓库审批权限";
            List<String> roleCodesList = bossUserService.getRoleCodesByUser(loginUser);
            // 财务审批 -> 仓库审批
            if(ListUtils.listIn(Constant.ROLE_CODE_LIST.get(1), roleCodesList) != -1) {
                // 仓库确认
                if(yOrNo) {
                    orgOrder.setOrgOrderStatus(OrgOrder.OrgOrderStatus.warehousePass);
                    List<OrderInfo> orderInfos = orderInfoRepository.findByOrders(orgOrder);
                    // 获取默认boss对应的 部门组织
                    SysSection numberOne = sysSectionService.getNumberOne();
                    for (OrderInfo orderInfo : orderInfos) {
                        // 修改boss 端库存
                        orgStockChangeService.orderInfo2Stock(numberOne, orderInfo, StockChangeRecord.ChangeDirection.reduce, StockChangeRecord.ChangeType.adjust);
                    }
                }else {
                    orgOrder.setOrgOrderStatus(OrgOrder.OrgOrderStatus.warehouseRefuse);
                }
                // 给 门店（采购发起人） 发消息
                approvalMessageService.messageToBuyer(orgOrderId);

                judge = "";
            }
        }else if(orgOrder.getOrgOrderStatus().toString().equals(OrgOrder.OrgOrderStatus.warehousePass.toString())) {
            judge = "你无门店确认到货权限";
            if(loginUser instanceof OrgUser) {
                if(loginUser.getId().toString().equals(orgOrder.getStaffUser().getId().toString())) {
                    // 门店确认到货
                    if(yOrNo) {
                        orgOrder.setOrgOrderStatus(OrgOrder.OrgOrderStatus.orgPass);
                        // 002： 自动生成库存变动记录, 修改 门店下 对应商品库存
                        List<OrderInfo> orderInfos = orderInfoRepository.findByOrders(orgOrder);
                        for (OrderInfo orderInfo : orderInfos) {
                            orgStockChangeService.orderInfo2Stock(orgOrder.getStaffUser().getSection(), orderInfo, StockChangeRecord.ChangeDirection.add, StockChangeRecord.ChangeType.adjust);
                        }
                    }else {
                        orgOrder.setOrgOrderStatus(OrgOrder.OrgOrderStatus.orgRefuse);
                        // 002： 返还 boss 端 库存
                        List<OrderInfo> orderInfos = orderInfoRepository.findByOrders(orgOrder);
                        // 获取默认boss对应的 部门组织
                        SysSection numberOne = sysSectionService.getNumberOne();
                        for (OrderInfo orderInfo : orderInfos) {
                            orgStockChangeService.orderInfo2Stock(numberOne, orderInfo, StockChangeRecord.ChangeDirection.add, StockChangeRecord.ChangeType.adjust);
                        }
                    }
                    judge = "";
                }
            }
        }else {
            throw new AdminException("此采购单状态不再支持审批");
        }
        orgOrder.setPassTime(System.currentTimeMillis());
        // 修改采购单状态
        dao.modify(orgOrder);
        if(StringUtils.isNotBlank(judge)) {
            throw new AdminException(judge);
        }

        return orgOrder;
    }

    /**
     * 只删除 采购单
     * @param orgOrder
     * @return
     * @throws AdminException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrgOrder update(OrgOrder orgOrder) throws AdminException {

        orgOrder.setLastModifyTime(System.currentTimeMillis());
        SysUser user = sysUserService.getUser();
        orgOrder.setUpdateUser(user);

        entityManager.merge(orgOrder);

        entityManager.flush();

        return orgOrder;
    }
}
